<?php
/**
 * Classe Observer pour une commande de correction pour
 * - compter le nombre de mots
 * - changer la quantité
 * - recalculer le prix
 * @author NICPLE
 *
 * The event is raised in the class Mage_Catalog_Model_Product_Type_Price→getFinalPrice()
 * Mage::dispatchEvent(’catalog_product_get_final_price’,array(’product’⇒$product));
 */

ini_set('display_errors', 0);
error_reporting(E_ALL);
$_SERVER['MAGE_IS_DEVELOPER_MODE'] = "true";

define("DOC_AU_MOT_ATTRIBUTSET","Documents au mot");
define("FILE_SEPARATOR",".");

define("JRE_URI","conf_jre_uri");
define("SCRIPT_JAVA","app/code/local/Orthographe/WordCounter/java/");

define("PERCENT","percent");
define("FIXE","fix");

define("DELAY_TREATEMENT","Délais de traitement");

define("DELAY_TREATEMENT_MESSAGE","cmd_delay_message");

define("CUSTOM_VAR_DEFAULT_DELAY_RESPONSE","cmd_default_delayresponse_bigseuil");



class Orthographe_WordCounter_Model_Observer extends Varien_Event_Observer
{
	public function __construct()
	{
	}


	private $_typeDelayTreatmentQuoteItem ="";


	/**
	 * Update the Quote Item of the Cart with the number of Words count in the uploaded document
	 * @param Varien_Event_Observer $observer checkout_cart_product_add_after
	 */
	public function updateQuoteInCartWithDocument(Varien_Event_Observer $observer) {

		// 		Mage::log("NPL - ".get_class($this)." -***************** updateQuoteInCartWithDocument ",Zend_Log::DEBUG);

		Mage::log("NPL - ".get_class($this)." -BEGIN Update QuoteItem after adding product - observer : checkout_cart_product_add_after");

		//Récupération du QuoteItem= article ajouté
		$quoteItem = $observer->getEvent()->getQuoteItem();
		$quoteItemID = $quoteItem->getQuoteId();
		Mage::log("NPL - ".get_class($this)." -Observer QUOTE ITEM ".$quoteItemID,Zend_Log::DEBUG);

		// 		Mage::log($quoteItem->debug(),Zend_Log::DEBUG);
		//Get related Product
		$product = $observer->getEvent()->getProduct();
		// 		Mage::log($product->debug(),Zend_Log::DEBUG);


		//Check the new Product AttributeSet to test if it's a document au mot : DOC_AU_MOT_ATTRIBUTSET
		$attributeSetModel = Mage::getModel("eav/entity_attribute_set");
		$attributeSetModel->load($product->getAttributeSetId());
		$attributeSetName  = $attributeSetModel->getAttributeSetName();
		if(0 == strcmp($attributeSetModel->getAttributeSetName(), DOC_AU_MOT_ATTRIBUTSET)){
			Mage::log("NPL - ".get_class($this)." -Product is a ".DOC_AU_MOT_ATTRIBUTSET." - ".$attributeSetName,Zend_Log::DEBUG);

			if(!empty($_FILES)){
				Mage::log('NPL - QUOTE ITEM ".$quoteItemID." - Il y a au moins 1 fichier -> traitement pour récupérer le fichier',Zend_Log::INFO);

				//Récupération un tableau contenant l'adresse de stockage du fichier.
				$arFileDescription = $this->getLocalFileFullPath($quoteItem);


				Mage::log("NPL - ".get_class($this)." -Try to Read the uploaded local file @ ".$arFileDescription['fullpath'],Zend_Log::DEBUG);


				if(file_exists($arFileDescription['fullpath']) && filesize($arFileDescription['fullpath']) > 1){
					Mage::log("NPL - ".get_class($this)." - Temp file existe bien ; comptage du nombre de mots ",Zend_Log::DEBUG);
					$nrbMotFile = $this->countWord($arFileDescription['fullpath'],$arFileDescription['filename'],$arFileDescription['filename']);

					Mage::log("NPL - ".get_class($this)." -QUOTE ITEM ".$quoteItemID." - Nombre de mots ".$nrbMotFile." dans le fichier : ".$arFileDescription['fullpath'],Zend_Log::INFO);

					Mage::log("NPL - ".get_class($this)." -QUOTE ITEM ".$quoteItemID." - Quantité Avant ".$quoteItem->getQty(),Zend_Log::DEBUG);

					$quoteItem->setQty($nrbMotFile);
					Mage::log("NPL - ".get_class($this)." -QUOTE ITEM ".$quoteItemID." - Quantité Après ".$quoteItem->getQty(),Zend_Log::DEBUG);
					//Getting Array for new Price
					$arChangeUnitWordCost = $this->changeUnitWordCost($product,$nrbMotFile);

					$quoteItem->getProduct()->setPrice($arChangeUnitWordCost["finalCost"]);
					Mage::log("NPL - ".get_class($this)." -Final Unit Cost per Word to apply = ".$arChangeUnitWordCost["finalCost"]." - Original Quote Item Price ".$quoteItem->getPrice(),Zend_Log::INFO);

					$quoteItem->setPrice($arChangeUnitWordCost["finalCost"]);
					$quoteItem->setBaseCalculationPrice($arChangeUnitWordCost["finalCost"]);
					$quoteItem->setCalculationPrice($arChangeUnitWordCost["finalCost"]);
					$quoteItem->setBaseOriginalPrice($arChangeUnitWordCost["finalCost"]);
					//Assign the new Original Custom Price !

					$quoteItem->setSeuil(intval($arChangeUnitWordCost["seuil"]));

					$quoteItem->setOriginalCustomPrice(
							$this->applyNewCostWithOptions($quoteItem,
									floatval($arChangeUnitWordCost["finalCost"])
							)
					);

					// 					$quoteItem->getProduct()->setPrice($newUnitCost);
					$quoteItem->getProduct()->setIsSuperMode(true);

					$quoteItem->calcRowTotal();

					$quote = $quoteItem->getQuote();
					$quote->collectTotals();
					$quote->save();


					Mage::log("NPL - ".get_class($this)." - Quote Id saved =".$quote->getID(),Zend_Log::DEBUG);
					Mage::log("NPL - ".get_class($this)." - Quote ITEM Id saved =".$quoteItem->getID(),Zend_Log::DEBUG);

					//Save the Ajuste_Quote_Item
					$ajusteQuoteItem = Mage::getModel('wordcounter/ajuste_quote_item');
					// 					Mage::log("NPL - ".get_class($this)." -AjusteQuoteItem = ".print_r($ajusteQuoteItem,true),Zend_Log::DEBUG);
					$ajusteQuoteItem->setData('seuil',$quoteItem->getSeuil());
					$ajusteQuoteItem->setInitialDelay(($quoteItem->getInitialDelay()));
					//Push Final delay depending the treatment



					switch(intval($quoteItem->getSeuil())) {
						case 1:
						case 2:
							$ajusteQuoteItem->setFinalDelay(($quoteItem->getFinalDelay()));
							break;
						case 3:
							$ajusteQuoteItem->setFinalDelay(
							Mage::getModel('core/variable')->loadByCode(CUSTOM_VAR_DEFAULT_DELAY_RESPONSE)->getValue('plain')
							);
							break;
						default:
							$ajusteQuoteItem->setFinalDelay(0);
							break;
					}



					Mage::log("NPL - ".get_class($this)." - _typeDelayTreatmentQuoteItem ".$this->_typeDelayTreatmentQuoteItem,Zend_Log::DEBUG);
					$ajusteQuoteItem->setTypeDelay($this->_typeDelayTreatmentQuoteItem);
					$ajusteQuoteItem->setData('quote_item_id',$quoteItem->getID());

					//fullFilePathUploaded
					$ajusteQuoteItem->setClientInitFile($arFileDescription['fullpath']);
					$ajusteQuoteItem->setClientInitFilename($arFileDescription['filename']);

					Mage::log("NPL - ".get_class($this)." -AjusteQuoteItem = ".print_r($ajusteQuoteItem,true),Zend_Log::DEBUG);

					try{
							
						$result = $ajusteQuoteItem->save();
						Mage::log("NPL - ".get_class($this)." - Successfully AjusteQuoteItem saved".$ajusteQuoteItem->getID(),Zend_Log::INFO);

					}catch(Exception $e) {
						Mage::log("NPL - ".get_class($this)." - Saving Ajuste_Quote_Item impossible ! : ".$e->getMessage(),Zend_Log::ERR);
					}

					Mage::log("NPL - ".get_class($this)." -Final Unit Cost per Word to apply = ".$arChangeUnitWordCost["finalCost"]." - Final QuoteItem Price ".$quoteItem->getPrice(),Zend_Log::DEBUG);


				}else{
					Mage::log("NPL - ".get_class($this)." -QUOTE ITEM ".$quoteItemID." -  Error Temp file does not exist or is empty: ",Zend_Log::ERR);
					throw Mage::throwException($this->__('File uploaded does not exist @ : '.$arFileDescription['fullpath']));
				}

			}else {
				Mage::log("ERR_FILE Fichier vide ko=".$_FILES[$key]['size'],Zend_Log::ERR);
				// 				Mage::throwException($this->__('No file uploaded.'));
			}


		}else{
			Mage::log("NPL - ".get_class($this)." -Product is not a ".DOCUMENT_AU_MOT_ATTRIBUTSET." -> ".$attributeSetName,Zend_Log::DEBUG);
		}



		Mage::log("NPL - ".get_class($this)." -END Update Quote after adding product");
	}

	/**
	 * Apply Options with new Unit price
	 * - Delay :
	 *    - if seuil = 2 ==> delay = delay + 24h
	 *    - if seuil = 3 ==> delay = 0 (inform Customer)
	 * @param Orthographe_WordCounter_Model_Quote_Item $quoteItem
	 * @param float $newUnitPrice
	 * @return number
	 */
	private function applyNewCostWithOptions(Orthographe_WordCounter_Model_Quote_Item $quoteItem, $newUnitPrice) {

		Mage::log("NPL - ".get_class($this)." -BEGIN Applying new Cost for QuoteITEM ID {$quoteItem->getID()} with Options - New Unit Price = ${newUnitPrice} - Seuil = ".$quoteItem->getSeuil(),Zend_Log::INFO);

		//Getting the whole selected options
		$arOptions = $quoteItem->getProduct()->getTypeInstance(true)->getOrderOptions($quoteItem->getProduct());

		//Getting all Mage_Sales_Model_Quote_Item_Option
		if(Mage::getIsDeveloperMode())
		foreach ($quoteItem->getOptionsByCode() as $quoteItemOption){
			Mage::log("NPL - ".get_class($this)." -Quote ItemOption Class = ".get_class($quoteItemOption),Zend_Log::DEBUG);
			Mage::log("NPL - ".get_class($this)." -Quote ItemOption Code = ".$quoteItemOption->getCode(),Zend_Log::DEBUG);
			Mage::log("NPL - ".get_class($this)." -Quote ItemOption Value = ".$quoteItemOption->getValue(),Zend_Log::DEBUG);
			Mage::log("NPL - ".get_class($this)." -Quote ItemOption ItemID = ".$quoteItemOption->getItemId(),Zend_Log::DEBUG);
		}


		//Sum of the options
		$sumOptions = 0;

		//Pass thrue the different custom options
		foreach($arOptions["options"] as $customOption) {
			$bApplyOptionPrice = true;
			/*Mage::log($customOption['label'],Zend_Log::DEBUG);
			 Mage::log($customOption['value'],Zend_Log::DEBUG);
			Mage::log($customOption['print_value'],Zend_Log::DEBUG);
			Mage::log($customOption['option_id'],Zend_Log::DEBUG);
			Mage::log($customOption['option_type'],Zend_Log::DEBUG);
			Mage::log($customOption['option_value'],Zend_Log::DEBUG);
			Mage::log($customOption['custom_view'],Zend_Log::DEBUG);*/
			Mage::log("Initial custOption = ".print_r($customOption,true),Zend_Log::DEBUG);

			Mage::log("NPL - ".get_class($this)." -Custom option activated ==> ".$customOption['label']." / value = ".$customOption['value'],Zend_Log::DEBUG);

			// 			// Method 2 (Quicker, Recommended)
			// 			$collection = Mage::getModel('catalog/product_option_value')->getCollection();
			// 			Mage::log("Query product_option_value = ".$collection->getSelect(),Zend_Log::DEBUG);

			//Mage_Catalog_Model_Product_Option_Value
			//->addFieldToFilter('main_table.option_type_id',$valuesId)
			//Getting the catalog production options bye ID
			if(intval($customOption['option_value'])){
				try {
					$value = Mage::getModel('catalog/product_option_value')->getCollection()
					->getValuesByOption($customOption['option_value'])
					//->addFieldToFilter("main_table.option_type_id", $customOption['option_value'])
					->addTitleToResult(Mage::app()->getStore()->getId())
					->addPriceToResult(Mage::app()->getStore()->getId())
					->getFirstItem();

					// 					Mage::log("NPL - ".get_class($this)." -Value Option = ".print_r($value,true),Zend_Log::DEBUG);

					Mage::log("NPL - ".get_class($this)." -Valuable cust option retrieve ==> Title = ".$customOption["label"]." /
							Price = ".$value->getPrice()." /
									Type = ".$value->getPriceType(),Zend_Log::DEBUG);


					//Manage Delay Message for SKU Timer regarding $seuil & option
					if($customOption['label'] == DELAY_TREATEMENT){
						//Affect the value of the type of treatment delay
						$this->_typeDelayTreatmentQuoteItem = $customOption['value'];

						$messageDelay = "";
						Mage::log("NPL - ".get_class($this)." - Seuil of the Quote Item = ".$quoteItem->getSeuil(),Zend_Log::DEBUG);

						Mage::log("NPL - ".get_class($this)." -Setting the Initial Delay = ".$value->getSku(),Zend_Log::INFO);
						$quoteItem->setInitialDelay(intval($value->getSku()));

						switch($quoteItem->getSeuil()){
							case 1:
								Mage::log("NPL - ".get_class($this)." -Quote item with Sueil N°1 = {$quoteItem->getSeuil()} ApplyOption =".$bApplyOptionPrice,Zend_Log::INFO);

								Mage::log("NPL - ".get_class($this)." -Setting the Final Delay = ".$value->getSku(),Zend_Log::INFO);
								$quoteItem->setFinalDelay(intval($value->getSku()));

								break;
							case 2 :
								Mage::log("NPL - ".get_class($this)." -Quote item with Sueil N°2 = {$quoteItem->getSeuil()} ApplyOption =".$bApplyOptionPrice,Zend_Log::INFO);
								//Affichage du message de temps de traitement.
									
								Mage::log("NPL - ".get_class($this)." -Setting the Final Delay = ".$value->getSku()+24,Zend_Log::INFO);
								$quoteItem->setFinalDelay(intval($value->getSku()+24));
									
								break;
							case 3 :

								$bApplyOptionPrice = false;
									
								//Affichage du message de temps de traitement.

									
									
								Mage::log("NPL - ".get_class($this)." -Quote item with Sueil N°3 = {$quoteItem->getSeuil()} ApplyOption =".$bApplyOptionPrice,Zend_Log::INFO);
								break;
						}
						//Notice with the DelayMessage
						Mage::getSingleton("core/session")->addNotice(Mage::helper('orthographewordcounter')->getDelayMessage($quoteItem,$quoteItem->getFinalDelay()));

						Mage::log("NPL - ".get_class($this)." -END Applying new Cost for QuoteITEM ID {$quoteItem->getID()}",Zend_Log::INFO);
							
					}



					//Check if the option influence the word unit price
					if($bApplyOptionPrice){
						switch($value->getPriceType()){
							case PERCENT :
								Mage::log("NPL - ".get_class($this)." -SUM options before applying Percentage = ".$sumOptions,Zend_Log::DEBUG);
								$sumOptions += ($newUnitPrice*(($value->getPrice())/100));
								Mage::log("NPL - ".get_class($this)." -New SUM options after applying Percentage = ".$sumOptions,Zend_Log::DEBUG);
								break;
							default :
								//$newUnitPrice;
								break;
						}
					}

				}catch(Exception $e) {
					Mage::log("NPL - ".get_class($this)." - Getting Custom Option details is not possible !".$e->getMessage(),Zend_Log::ERR);
				}
			}else{
				Mage::log("NPL - ".get_class($this)." -option_value has not to be apply on price !".$customOption['option_value'],Zend_Log::DEBUG);
			}

		}
		$totalUnitPriceWithOptions = $newUnitPrice+$sumOptions;

		//Saving quoteItem :
		// 		$quoteItem->save();
		Mage::log("NPL - ".get_class($this)." -New Unit Price with options  = ".$totalUnitPriceWithOptions,Zend_Log::INFO);
		return $totalUnitPriceWithOptions;

}

/**
 * Get the Price regarding the nbr of Words in the files and the "seuils"
 * @param Mage_Catalog_Model_Product $product
 * @param Integer $nbrMotFile
 * @return array $arChangeUnitWordCost
 * 		finalCost => float Unit cost updated
 * 		seuil => integer 1 / 2 / 3
 */
private function changeUnitWordCost(Mage_Catalog_Model_Product $product, $nbrMotFile){

	Mage::log("NPL - ".get_class($this)." -Nombre de mots à analyser :  ".$nbrMotFile,Zend_Log::DEBUG);
	$max_seuil1 = $product->getResource()->getAttribute('max_seuil1')->getFrontend()->getValue($product);
	$max_seuil2 = $product->getResource()->getAttribute('max_seuil2')->getFrontend()->getValue($product);



	$finalCost = $product->getPrice();
	$seuil = 0;
	switch($nbrMotFile){
		case ($nbrMotFile < intval($max_seuil1)) :
			$finalCost = $product->getPrice();
			Mage::log("NPL - ".get_class($this)." -Inferieur au 1er seuil Apply  :  ".$finalCost,Zend_Log::DEBUG);
			$seuil=1;
			break;
		case ($nbrMotFile < intval($max_seuil2) ):
			$finalCost = $product->getResource()->getAttribute('prix_u_seuil2')->getFrontend()->getValue($product);
			Mage::log("NPL - ".get_class($this)." -Inferieur au 3eme seuil Apply  :  ".$finalCost,Zend_Log::DEBUG);
			$seuil=2;
			break;
		default :
			$finalCost = $product->getResource()->getAttribute('prix_u_seuil3')->getFrontend()->getValue($product);
			Mage::log("NPL - ".get_class($this)." -Supérieur au 3eme seuil Apply  :  ".$finalCost,Zend_Log::DEBUG);
			$seuil=3;
			break;
	}


	Mage::log("NPL - ".get_class($this)." -Final Cost return :  ".$finalCost,Zend_Log::DEBUG);

	$arChangeUnitWordCost = array(
			"finalCost" => $finalCost,
			"seuil" => $seuil
	);

	return $arChangeUnitWordCost;
}

/**
 * Fonction récupérant de la base la localisation sur le disque du fichier uploader
 * @param Mage_Sales_Model_Quote_Item $quoteItem
 * @return  $array file description : <br>
 *    'fullpath' = full local path to the QuoteItem File
 *    'filename' = name of the file
 */
private function getLocalFileFullPath(Mage_Sales_Model_Quote_Item $quoteItem) {

	//Get Custom Option list of the quote item
	if(empty($quoteItem)){
		Mage::log("NPL - ".get_class($this)." - QuoteItem is Empty",Zend_Log::DEBUG);
		Mage::throwException($this->__('QuoteItem empty !.'));
	}

	//Getting the whole selected options
	$arOptions = $quoteItem->getProduct()->getTypeInstance(true)->getOrderOptions($quoteItem->getProduct());

	//Pass thrue the different custom options
	foreach($arOptions["options"] as $customOption) {

		Mage::log("NPL - ".get_class($this)." -File Custom option = ".print_r($customOption,true),Zend_Log::DEBUG);

		try {
			$value = unserialize($customOption['option_value']);
			// 				Mage::log("NPL - ".get_class($this)." - ///////////////////////////////////////////////////// ",Zend_Log::DEBUG);
			// 				Mage::log(print_r($value,true),Zend_Log::DEBUG);
			// 				Mage::log("NPL - ".get_class($this)." - ///////////////////////////////////////////////////// ",Zend_Log::DEBUG);

			if(!empty($value['type']) && strcasecmp($value['type'],"application/octet-stream")==0){
				$arFileDescription = array(
						"fullpath" => "",
						"filename" => "",
						"type" => "",
						"size" =>0
				);
				//Mage::log(print_r($value,true),Zend_Log::DEBUG);

				Mage::log("NPL - ".get_class($this)." -Custom Option is A FILE stock : ".$value['fullpath'],Zend_Log::INFO);

				$arFileDescription['fullpath']=$value['fullpath'];
				$arFileDescription['filename']=$value['title'];
				$arFileDescription['type']=$value['type'];
				$arFileDescription['size']=$value['size'];

				return $arFileDescription;
			}else{
				Mage::log("NPL - ".get_class($this)." -Custom Option is not an application/octet-stream - ID= ".$customOption['option_id'],Zend_Log::DEBUG);
			}

		}catch(Exception $e) {
			Mage::log("NPL - ".get_class($this)." - Custom option is not serialized !".$e->getMessage(),Zend_Log::DEBUG);
		}
	}
}

/**
 * Fonction qui retourne le nombre de mot d'un fichier passé en paramètre selon son extension
 * Extensions gérées : .txt
 *
 * @param string $urlFileUploaded - url complète du fichier à ouvrir
 * @param string $fileRenameUploadedName - nom physique du fichier à ouvrir
 * @param string $fileUploadName - nom original du fichier uploader de type : txt, doc, docx, ppt, pptx
 * @return mixed nombre de mots
 */
private function countWord($urlFileUploaded,$fileRenameUploadedName,$fileUploadName) {

	$extensionFileName=$this->extractExtensionUploadedFile($urlFileUploaded);
	try{
		switch ($extensionFileName) {
			case "txt" :
				Mage::log("Extension TXT",Zend_Log::INFO);
				return $this->countWordForTXTFile($urlFileUploaded);
				break;
			case "doc" :
				Mage::log("Extension DOC",Zend_Log::INFO);
				// 				return $this->countWordForDOCFile($urlFileUploaded);
				return $this->countWordForDOCFile($urlFileUploaded,"DOC");
				break;
			case "docx" :
				Mage::log("Extension DOCX",Zend_Log::INFO);
				return $this->countWordForDOCXFile($urlFileUploaded);
				break;
			case "ppt" :
				Mage::log("Extension PPT",Zend_Log::INFO);
				return $this->countWordForDOCFile($urlFileUploaded,"PPT");
				break;
			case "pptx" :
				Mage::log("Extension PPTX",Zend_Log::INFO);
				return $this->countWordForDOCXFile($urlFileUploaded);
				break;
			default:
				Mage::log("Erreur, l'extension n'est pas reconnue !",Zend_Log::ERR);
				Mage::throwException($this->__('Extension not identified : '.$extensionFileName));
				break;
		}
	} catch(Exception $e){
		Mage::log("Erreur lors du comptage de : ".$fileUploadName." with extension :".$extensionFileName." - ".$e->getMessage(),Zend_Log::ERR);
		Mage::throwException($this->__('Error while reading the file to count Words.'));
	}

}

/**
 * Retourne l'extension du fichier uploader
 * @param string fullPathName - url du du fichier
 */
private function extractExtensionUploadedFile($fullPathName) {

	$fileExtention = pathinfo($fullPathName,PATHINFO_EXTENSION);


	Mage::log("FileName = ".$fullPathName." / File Extension = ".$fileExtention,Zend_log::DEBUG);
	return $fileExtention;
}

/**
 * Compte le nombre de mots d'un fichier Texte
 * @param string $file
 */
private function countWordForTXTFile($file) {

	Mage::log("Fichier TXT - Fichier à ouvrir : ".$file,Zend_Log::DEBUG);

	try {
		$fp=fopen($file,"r");
		//if(!$fp){
		Mage::log("Fichier ouvert : ".$file,Zend_Log::DEBUG);
		$wholeContent = fread($fp,filesize($file));
		fclose($fp);

		unset($fp);

		Mage::log("Contenu récupéré : : ".$wholeContent,Zend_Log::DEBUG);

		$nbrFindWords=str_word_count($wholeContent,0);

		Mage::log(print_r(str_word_count($wholeContent, 1, 'éèêàáãç1234567890')));

		Mage::log("Nombre de mots : ".$nbrFindWords,Zend_Log::INFO);

		unset($wholeContent);

	}catch (Exception $e){
		//Throw Exception !!!
		Mage::log("Erreur tentative de lecture de : ".$file." - ".$e->getMessage(),Zend_Log::ERR);
		Mage::throwException($this->__('Error while opening the file to count Words.'));
	}

	return $nbrFindWords;

}

/**
 * Compte le nombre de mots d'un fichier DOCX ou PPTX
 * @param string $file full path for DOCX or PPTX
 * @return integer - number of words in the file
 */
private function countWordForDOCXFile($file){

	try {
		$zip = zip_open($file);

		if ($zip)
		{
			while ($zip_entry = zip_read($zip)){

				if(zip_entry_name($zip_entry)=="docProps/app.xml") {
					Mage::log("NPL - ".get_class($this)." -Fichier XML app.xml du Zip trouvé = ".zip_entry_name($zip_entry),Zend_Log::DEBUG);

					try{
						$content = zip_entry_read($zip_entry);
						Mage::log("NPL - ".get_class($this)." -Contenu app.xml ".$content,Zend_Log::DEBUG);

						$reader = new XMLReader();
						$reader->xml($content);
						$nbrFindWords = 0;
						while ($reader->read()){
							if($reader->nodeType == XMLREADER::ELEMENT)
								Mage::log("NPL - ".get_class($this)." -Balise = ".$reader->localName,Zend_Log::DEBUG);

							if($reader->nodeType == XMLREADER::ELEMENT &&  $reader->localName=="Words"){
								Mage::log("NPL - ".get_class($this)." -Words Found !! ".$reader->readString(),Zend_Log::DEBUG);
								$nbrFindWords = $reader->readString();


								break;
							}
						}

						Mage::log("NPL - ".get_class($this)." -Nombre de mots : ".$nbrFindWords,Zend_Log::INFO);

					}catch (Exception $e){
						Mage::log("Erreur tentative de lecture du app.xml : - ".$e->getMessage(),Zend_Log::ERR);
						Mage::throwException($this->__('Error while reading app.xml from the docx file to count Words.'));
					}

				}else{
					Mage::log("NPL - ".get_class($this)." -Fichier XML app.xml not found = ".zip_entry_name($zip_entry),Zend_Log::DEBUG);
				}
			}
		}
	} catch (Exception $e) {
		//Throw Exception !!!
		Mage::log("Erreur tentative de lecture du Zip : ".$file." - Est-ce un vrai docx ou pptx ?? \n".$e->getMessage(),Zend_Log::ERR);
		Mage::throwException($this->__('Error while opening the docx file to count Words.'));
	}

	unset($zip);
	unset($reader);
	unset($content);
	if(empty($nbrFindWords)){
		Mage::log("Erreur Impossible de récupérer le nombre de mot du document ".$file." - Est-ce un vrai docx ou pptx ?? \n",Zend_Log::ERR);
		Mage::throwException($this->__('Error while counting number of Word of a docx/pptx file.'));
	}else
		return $nbrFindWords;
}


/**
 * Compte le nombre de mots d'un fichier DOC
 * @param string $file
 * @param string $type : DOC || PPT
 */
private function countWordForDOCFile($file,$type) {

	Mage::log("Fichier DOC - Fichier à ouvrir : ".$file,Zend_Log::DEBUG);
	Mage::log("current dir =".$_SERVER['CONTEXT_DOCUMENT_ROOT']);
	// 		Mage::log(print_r($_SERVER,true));

	$urlScriptDir = $_SERVER['CONTEXT_DOCUMENT_ROOT'].SCRIPT_JAVA;

	$uriJRE=Mage::getModel('core/variable')->loadByCode(JRE_URI)->getValue('plain');
	
	Mage::log("Script to launch = ".$urlScriptDir." - JRE URI = {$uriJRE}");
	try {
		$retourFct=0;

		$script = $uriJRE." -cp ".$urlScriptDir."poi.jar;".$urlScriptDir."poi-scratchpad.jar;".$urlScriptDir.". orthographe.doc.count.CountWordDocFile ".$file." ".$type;
		Mage::log("NPL - ".get_class($this)." -Script to launch ".$script,Zend_Log::DEBUG);
		$resultNbrMots = system($script,$retourFct);

		Mage::log("NPL - ".get_class($this)." -DOC ".$file." retour appel externe =".$retourFct." / Words=".$resultNbrMots,Zend_log::INFO);

		$resultNbrMots=intval($resultNbrMots);

		if($resultNbrMots!=0)
			$nbrFindWords=$resultNbrMots;
		else{
			Mage::log("NPL - ".get_class($this)." -Error, nombre de mots non Integer pour le fichier retour=".$resultNbrMots." / file ".$file,Zend_Log::ERR);
			Mage::throwException($this->__('Error while reading # of words in a DOC file.'));
		}

	}catch (Exception $e){
		//Throw Exception !!!
		Mage::log("Erreur tentative de lecture de : ".$file,Zend_Log::ERR);
		Mage::log("Erreur : ".$e->getMessage(),Zend_Log::INFO);
		Mage::throwException($this->__('Error while opening the file to count Words.'));
	}

	return $nbrFindWords;

}


/**
 * Get Captcha String
 *
 * @param Varien_Object $request
 * @param string $formId
 * @return string
 */
protected function _getCaptchaString($request, $formId)
{
	$captchaParams = $request->getPost(Mage_Captcha_Helper_Data::INPUT_NAME_FIELD_VALUE);
	return $captchaParams[$formId];
}

/**
 * Break the execution in case of incorrect CAPTCHA
 *
 * @param Varien_Event_Observer $observer
 * @return Your_Module_Model_Observer
 */
public function checkCaptcha($observer)
{
	$formId = 'upload_form';
	$captchaModel = Mage::helper('captcha')->getCaptcha($formId);
	if ($captchaModel->isRequired()) {
		$controller = $observer->getControllerAction();
		if (!$captchaModel->isCorrect($this->_getCaptchaString($controller->getRequest(), $formId))) {
			Mage::getSingleton('customer/session')->addError(Mage::helper('captcha')->__('Incorrect CAPTCHA.'));
			$controller->setFlag('', Mage_Core_Controller_Varien_Action::FLAG_NO_DISPATCH, true);
			Mage::getSingleton('customer/session')->setCustomerFormData($controller->getRequest()->getPost());
			$controller->getResponse()->setRedirect(Mage::getUrl('*/*/index'));
		}
	}

	return $this;
}


}
